package org.iabako.server.controller.timer.logtrack;

import org.apache.log4j.Logger;
import org.iabako.server.dao.business.NotificationDAO;
import org.iabako.server.dao.business.TrackingDAO;
import org.iabako.server.dao.user.UserDAO;
import org.iabako.server.tools.ServerTools;
import org.iabako.shared.entity.business.NotificationEmail;
import org.iabako.shared.entity.business.Tracking;
import org.iabako.shared.entity.user.User;
import org.iabako.shared.tools.GenericTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * Created by jose on 18/05/15.
 */

@Controller
public class ActivityLogTrackController {

    static Logger log = Logger.getLogger(ActivityLogTrackController.class.getName());

    private final static String POSTFIX_MAIL_LOG = "/var/log/mail.log";

    @Autowired
    private UserDAO userDAO;
    @Autowired
    private NotificationDAO notificationDAO;
    @Autowired
    private TrackingDAO trackingDAO;

    public String trackActivitiesLogs() {
        log.info("Executing ActivityLogTrackController...");

        ServerTools serverTools = new ServerTools();
        Date yesterday = serverTools.addDaysToDate(serverTools.resetTime(new Date()), -1);

        StringBuilder usersResult = new StringBuilder();
        StringBuilder notificationsResult = new StringBuilder();
        StringBuilder trackingResult = new StringBuilder();
        StringBuilder emailsResult = new StringBuilder();
        StringBuilder result = new StringBuilder();

        //Logged users
        List<User> users = userDAO.getLoggedUsersOn(yesterday);
        for (User user : users) {
            usersResult.append(GenericTools.formatTime(user.getLastLogin()) + " : " + user.getEmail() + " : " + user.getEnterprise().getName() + "\n");
        }

        //Notifications sent
        List<NotificationEmail> notifications = notificationDAO.getNotificationEmailsSentOn(yesterday);
        for (NotificationEmail notificationEmail : notifications) {
            User user = notificationEmail.getUser();
            notificationsResult.append(user.getEmail()
                    + " : " + user.getEnterprise().getName()
                    + " : " + notificationEmail.getNotification().getCardinal()
                    + " : " + notificationEmail.getNotification().getType().name() + "\n");
        }

        //Tracking
        List<Tracking> trackings = trackingDAO.getTrackingsOn(yesterday);
        for (Tracking tracking : trackings) {
            User user = tracking.getUser();
            trackingResult.append(GenericTools.formatTime(tracking.getDate())
                    + " : " + user.getEmail()
                    + " : " + user.getEnterprise().getName()
                    + " : " + tracking.getCardinal()
                    + " : " + tracking.getType().name() + "\n");
        }

        //Mails sent (we look for logs also in ".1" files because of log rotation)
        getMailsSent(emailsResult, POSTFIX_MAIL_LOG, yesterday);
        getMailsSent(emailsResult, POSTFIX_MAIL_LOG + ".1", yesterday);

        if (usersResult.length() > 0 || notificationsResult.length() > 0 || trackingResult.length() > 0 || emailsResult.length() > 0) {

            result.append("Dear Admin,\nThis is the activity tracking log of " + GenericTools.formatDate(yesterday) + " : \n");

            if (usersResult.length() > 0) {
                result.append("\n<b>LOGGED USERS : </b>\n").append(usersResult);
            }
            if (notificationsResult.length() > 0) {
                result.append("\n<b>NOTIFICATIONS SENT : </b>\n").append(notificationsResult);
            }
            if (trackingResult.length() > 0) {
                result.append("\n<b>TASKS TRACK : </b>\n").append(trackingResult);
            }
            if (emailsResult.length() > 0) {
                result.append("\n<b>EMAILS SENT : </b>\n").append(emailsResult);
            }
        }

        return result.toString();
    }

    private void getMailsSent(StringBuilder emailsResult, String postfixMailLog, Date yesterday) {
        try {
            BufferedReader br = new BufferedReader(new FileReader(postfixMailLog));
            for (String line; (line = br.readLine()) != null; ) {
                String dateString = line.contains(" app postfix/") ? line.substring(0, line.indexOf(" app postfix/")) : null;
                if (dateString == null) {
                    continue;
                }
                Date date = new ServerTools().resetTime(ServerTools.getDateFromPostFixLogs(dateString));

                if (date.compareTo(yesterday) == 0) {
                    if (line.contains("to=<")) {
                        String email = line.substring(line.indexOf("to=<") + 4, line.indexOf(">,"));
                        boolean sent = line.contains("status=sent");
                        emailsResult.append(date + " : " + email + " : " + (sent ? "OK" : "ERROR") + "\n");
                    }
                }
            }
        } catch (FileNotFoundException e) {
            log.warn("This file does not exist in system file : " + postfixMailLog);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

}
